package com.huilian.tool.meituan.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.huilian.tool.meituan.config.MiddlewareConfig;
import com.huilian.tool.meituan.controller.ControllerException;
import com.huilian.tool.meituan.enums.FunctionEnum;
import com.huilian.tool.meituan.po.RequestModel;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 谢洛涛
 * @date 2021/1/9 15:46
 */
@Slf4j
public class HttpUtils {

    /**
     * 通过请求返回的内容进行验签
     *
     * @param response
     * @return
     */
    public static Map<String, Object> getResultData(String response) {
        log.info("请求返回的内容：{}", response);
        Map<String, Object> result = JSON.parseObject(response, Feature.OrderedField);
        final String sign = (String) result.get("sign");
        result.remove("sign");
        final String content = JSON.toJSONString(result);
        if (!RsaUtil.verifySign(content, sign, MiddlewareConfig.PublicKey)) {
            log.info("验签失败");
            throw new ControllerException("验签失败");
        }
        return result;
    }
    public static String format(HashMap<String,String> agencyConfig, Object reqParam, FunctionEnum functionEnum) {
        RequestModel requestModel = createRequestModel(agencyConfig,reqParam, functionEnum);
        String body = JSON.toJSONString(requestModel);
        log.info("请求的内容：{}", body);
        String sign = RsaUtil.sign(body, agencyConfig.get("privateKey"));
        requestModel.setSign(sign);
        return JSON.toJSONString(requestModel);
    }
    private static RequestModel createRequestModel(HashMap<String,String> agencyConfig, Object reqParam, FunctionEnum functionEnum) {
        RequestModel requestModel = new RequestModel();
        requestModel.setAgencyNo(agencyConfig.get("isvOrgId"));
        requestModel.setTimestamp(new Timestamp(System.currentTimeMillis()).toString());
        requestModel.setFunction(functionEnum.getCode());
        requestModel.setContent(JSON.toJSONString(reqParam));
        requestModel.setPayCompany("helipay");
        return requestModel;
    }
}
